package extension.game.zone;

import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
import extension.game.poker.PokerFlag;
import java.util.LinkedList;
import java.util.List;
import log.Debug;

public class JoinRoomHandler extends BaseServerEventHandler {

    @SuppressWarnings("unchecked")
    @Override
    public void handleServerEvent(ISFSEvent event) throws SFSException {
        User user = (User) event.getParameter(SFSEventParam.USER);
        Room room = (Room) event.getParameter(SFSEventParam.ROOM);
        Debug.i("handle join room request");
        Debug.d(user.getName() + ": join room " + room.getName());
        PokerZoneExtension ext = (PokerZoneExtension) getParentExtension();
        Response response = ext.getResponse();
        List<Room> listRooms;
        String groupName = RoomGroup.LEVEL1;
        if (room.getName().equals("The Lobby")) {
            groupName = (String) user.getProperty(Flag.GROUP_NAME);
            Debug.d("group name:" + groupName);
            if (groupName == null || groupName.length() == 0) {
                groupName = RoomGroup.LEVEL1;
                user.setProperty(Flag.GROUP_NAME, RoomGroup.LEVEL1);
                listRooms = ext.getParentZone().getRoomListFromGroup(RoomGroup.LEVEL1);
            } else {
                listRooms = ext.getParentZone().getRoomListFromGroup(groupName);
            }
            List<String> listRoomNames = new LinkedList<String>();
            List<Integer> listNumberPlayer = new LinkedList<Integer>();
            for (Room r : listRooms) {
                listRoomNames.add("#" + r.getName());
                Integer numberPlayers = (Integer) r.getProperty(PokerFlag.NUMBER_PLAYERS);
                if (numberPlayers != null) {
                    listNumberPlayer.add(numberPlayers);
                } else {
                    listNumberPlayer.add(0);
                }
            }
            response.sendListTable(listNumberPlayer, listRoomNames, groupName, user);
        }
    }
}
